const Article = require('../models/article')
const Tag = require('../models/tag')

const setOutput = require('../tools/setOutput').setOutput

class ArticleController {
  prefix = '' 
  getPath(name){
    return name ? `/${this.prefix}/${name}` : `/${this.prefix}`
  } 

  async add(ctx, next) {
    ctx.verifyParams({
      content: {type: 'string', required: true}
    }) 

    let obj = JSON.parse(JSON.stringify(ctx.request.body))  
     
    obj.createUserName = userInfo.userName
    obj.createName = userInfo.name
    obj.createId = userInfo._id
    
    const [addErr, res] = await to(new Article(obj).save())
  
    if(addErr) return ctx.throw(500, err) 
    ctx.response.body = setOutput(res.toJSON()) 
  }

  async find(ctx, next) {
    const {page = 1, pageSize = 20, tag} = ctx.request.query 
   
    const tagOpts = tag && {tags: tag} || {}
    const userOpts = { createId: userInfo._id } 

    const total = await Article.count({
      ...userOpts,
      ...tagOpts
    })
    
    const list = await Article.find({
      ...userOpts,
      ...tagOpts
    }) 
    .populate([{path:'tags', select: 'label desc'}])
    .sort({ createdTime: 'desc' }).skip((parseInt(page) - 1) * parseInt(pageSize)).limit(parseInt(pageSize) || 5).lean()
    const data = {
      list: list,
      total: total
    }
    ctx.response.body = setOutput(data, 'fetch')
  }

  async groupArticleByTag(ctx, next) { 
    const arr = [
      {
        '$match': { createId: userInfo._id }
      },
      {
        '$unwind': '$tags'
      },
      {
        '$group': {
          '_id': '$tags', 
          'count': {'$sum': 1}
        }
      }
    ]

    const countList = await Article.aggregate(arr)
    const tagList = await Tag.find().lean()  
    ctx.response.body = {
      data: {
        countList: countList,
        tagList: setOutput({list: tagList, total: 0}, 'fetch').data.list
      },
      code: 0,
      msg: '成功'
    } 
  }
}

module.exports = new ArticleController()